﻿using System;
using System.Collections.Generic;
using System.Text;

namespace TestEffectiveCS
{
    class Test13
    {
        //单例模式
        public class MySingleton1
        {
            private static readonly MySingleton1 _theOneAndOnly = new MySingleton1();

            private MySingleton1()
            {
                Console.Write("MySingleton1 私有构造器\n");
            }

            public static MySingleton1 TheOnly
            {
                get
                {
                    Console.Write("MySingleton1 获取单实例\n");
                    return _theOneAndOnly;
                }
            }
        }

        public class MySingleton2
        {
            private static readonly MySingleton2 _theOneAndOnly;
            //类型首次加载时，CLR会调用静态构造器
            //使用表态构造器可以捕获异常
            static MySingleton2()
            {
                try
                {
                    Console.Write("MySingleton2 静态构造器\n");
                    _theOneAndOnly = new MySingleton2();
                }
                catch (Exception Ex)
                {
                    Console.Write("处理 " + Ex.Message);
                }
            }

            private MySingleton2()
            {
                Console.Write("MySingleton2 私有构造器\n");

                throw new Exception("MySingleton2 私有构造器异常\n");
            }

            public static MySingleton2 TheOnly
            {
                get
                {
                    if (_theOneAndOnly == null)
                        Console.Write("MySingleton2 获取单实例失败\n");
                    else
                        Console.Write("MySingleton2 获取单实例成功\n");

                    return _theOneAndOnly;
                }
            }
        }

        public Test13()
        {
            MySingleton1 ms1 = MySingleton1.TheOnly;
            MySingleton2 ms2 = MySingleton2.TheOnly;
        }
    }
}
